package com.tzy.for10evalue.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

/**
 * 高德地图工具类
 * @author tzy
 * @date 2021/10/20 17:02
 */
@Slf4j
@Component
public class AmapUtil {
//    private static String key = "b830878104cfec7e50a6f12ee508647c";
    private static String key = "be8a87dc51eb694d10626fa15279f445";//dllocation

    /**
     * 地球半径,单位 km
     */
    private static final double EARTH_RADIUS = 6378.137;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 高德api 根据地址获取经纬度
     *
     * @param name
     * @return
     */
    public String getLatAndLogByName(String name) throws Exception {
        StringBuffer s = new StringBuffer();
        s.append("address=" + name + "&key=").append(key);
        String res = restSendGet("https://restapi.amap.com/v3/geocode/geo", s.toString());
        JSONObject jsonObject = JSONObject.parseObject(res);
        if(StringUtils.isEmpty(jsonObject.getString("geocodes"))){
            log.error("返回经纬度结果为空，res={}",res);
            throw new RuntimeException("返回经纬度结果为空");
        }
        JSONArray jsonArray = JSONArray.parseArray(jsonObject.getString("geocodes"));
        String location = ((JSONObject) jsonArray.get(0)).getString("location");
        return location;
    }

    /**
     * 高德api 根据地址获取经纬度
     *
     * @param name
     * {
     *     "formatted_address": "山东省青岛市城阳区鲜味岛",
     *     "country": "中国",
     *     "province": "山东省",
     *     "citycode": "0532",
     *     "city": "青岛市",
     *     "district": "城阳区",
     *     "township": [],
     *     "neighborhood": {
     *         "name": [],
     *         "type": []
     *     },
     *     "building": {
     *         "name": [],
     *         "type": []
     *     },
     *     "adcode": "370214",
     *     "street": [],
     *     "number": [],
     *     "location": "120.417493,36.297324",
     *     "level": "兴趣点"
     * }
     * @return
     */
    public JSONObject getGdLocationLatAndLogByName(String name) throws Exception {
        StringBuffer s = new StringBuffer();
        s.append("address=" + name + "&key=").append(key);
        String res = restSendGet("https://restapi.amap.com/v3/geocode/geo", s.toString());
        log.info("返回经纬度name={},结果:{}",name,res);
        JSONObject jsonObject = JSONObject.parseObject(res);
        if(StringUtils.isEmpty(jsonObject.getString("geocodes"))){
            log.error("返回经纬度结果为空，res={}",res);
            throw new RuntimeException("返回经纬度结果为空");
        }
        JSONArray jsonArray = JSONArray.parseArray(jsonObject.getString("geocodes"));
        return (JSONObject) jsonArray.get(0);
    }

    /**
     * 高德api 根据经纬度获取地址
     *
     * @param longitude
     * @param latitude
     * @return
     */
    public String getAddByAMAP(String longitude, String latitude) throws Exception {
        StringBuffer s = new StringBuffer();
        s.append("key=").append(key).append("&location=").append(longitude).append(",").append(latitude);
        String res = restSendGet("https://restapi.amap.com/v3/geocode/regeo?",s.toString());
        log.info(res);
        JSONObject jsonObject = JSONObject.parseObject(res);
        Assert.isTrue(!jsonObject.getString("infocode").equals("20011"), "服务级别不支持该经纬度");
        JSONObject jsonObject1 = (JSONObject) JSONObject.toJSON(jsonObject.get("regeocode"));
        String add = jsonObject1.get("formatted_address").toString();
        return add;
    }

  /*  @PostConstruct
    public void test() throws Exception{
//        judgeDistanceGreater1KM("浙江杭州市下城区永华街117号浙江明州康复医院门诊楼3楼库房","浙江杭州市下城区庆春路28号");
        getLatAndLogByName("浙江杭州市下城区永华街117号浙江明州康复医院门诊楼3楼库房");
    }*/


    public  Boolean judgeDistanceNew(double longitude1, double latitude1, double longitude2, double latitude2) {
        // 纬度
        double lat1 = Math.toRadians(latitude1);
        double lat2 = Math.toRadians(latitude2);
        // 经度
        double lng1 = Math.toRadians(longitude1);
        double lng2 = Math.toRadians(longitude2);
        // 纬度之差
        double a = lat1 - lat2;
        // 经度之差
        double b = lng1 - lng2;
        // 计算两点距离的公式
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(b / 2), 2)));
        // 弧长乘地球半径, 返回单位: 千米
        s =  s * EARTH_RADIUS;
        return s < 20;
    }

    /**
     * restTeplate 请求方式
     * */
    public String restSendGet(String url, String param) {
        String result = "";
        String urlName = url + "?" + param;
        try {
            String response = restTemplate.getForObject(urlName, String.class);
            result= response;
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return result;
    }
}
